<template>
  <div class="pad_10">
    <el-form ref="queryRef" :inline="true" label-width="68px">
      <el-form-item>
        <el-button @click="handleQuery">保存</el-button>
        <el-button @click="Cancel">取消</el-button>
        <el-button :disabled="!topicList.length" @click="lookSyatFun">预览试卷</el-button>
      </el-form-item>
    </el-form>
    <el-divider />
    <SetUserSelect
      :key="keys"
      ref="setUserSelect"
      class="queryForm"
      :labelwidth="100"
      :isShowUserBtn="false"
      :buttonIsShow="false"
      :formData="bill"
      :queryParams="datas"
      @kindFun="kindFun"
    ></SetUserSelect>
    <el-divider style="margin-bottom: 20px" content-position="left">试题</el-divider>
    <VxeTableGrid
      :key="keyTimemin"
      style="height: 320px"
      :tableColumn="fieldDefinitionColumn"
      :tableLoading="tableLoading"
      :dataList="topicList"
      :showPagination="false"
      :paginationParams="paginationParams"
    >
    </VxeTableGrid>
    <el-dialog v-model="dialogFormVisible" title="预览">
      <div class="card_box">
      <el-card class="box-card" shadow="never" v-for="(item, index) in result" :key="index">
        <template #header>
          <div class="card-header">
            <span>{{ index+1 + '、' }}{{ item.topic }} </span>
            <!-- <span v-show="istrueFun(item.answerType, item.correct)" style="color: red;"> (正确答案是：{{ item.correct }})</span> -->
          </div>
        </template>
        <div v-for="(items) in item.answerList" :key="items.id" style="pointer-events: none;">
          <el-checkbox v-model="items.cheakTrue" :label="items.type+items.topic" size="large" />
        </div>
      </el-card>
    </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button  @click="dialogFormVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
  </div>
</template>
<script setup lang="tsx">
import { ref, getCurrentInstance, watch } from "vue";
import { drugList  } from "@/api/basicManagement/varietyMana";
import { addpaper, paperId, eitHpaper, listall  } from "@/api/examPaperManaMin";
import { topicList as setdata  } from "@/api/questionManag";
import data from "./data";
import { useRoute } from "vue-router";
const { bill, datas } = data;
datas.value = {
  status: '1',
  totalScore: 100
}
const keyTimemin = ref(null);
let tableLoading = ref(false);
const { proxy } = getCurrentInstance();
let proxys: any = proxy;
const route: any = useRoute();
let keys = ref(0)
const { paper_mana_kind, paper_mana_status, paper_object_ype } = proxys.useDict("paper_mana_kind", "paper_mana_status", "paper_object_ype");
const paginationParams = ref({
  total: 12,
  pageNum: 1,
  pageSize: 10000,
});
const kindFun = (val) => {
  if (val.val == 1) {
    datas.value.totalScore = 0
  } else {
    datas.value.totalScore = 100
  }
};
const dialogFormVisible = ref(false)
let result = ref([])
const lookSyatFun = () => {
  dialogFormVisible.value = true
  result.value = []
  let arr2Mapstr = {};
  topicList.value.forEach((item) => arr2Mapstr[item.topicId] = item)
  for(let item in arr2Mapstr) {
    for (let i = 0; i < arr2Map.value.length; i++) {
      if (arr2Map.value[i].id == item) {
        result.value.push(arr2Map.value[i])
      }
    }
  }
}
watch(
  paper_mana_kind,
  (newV, oldV) => {
    bill.value[1].selectData = paper_mana_kind.value;
    keys.value = new Date().getTime();
  }
);
watch(
  paper_mana_status,
  (newV, oldV) => {
    bill.value[2].selectData = paper_mana_status.value;
    keys.value = new Date().getTime();
  }
);
watch(
  paper_object_ype,
  (newV, oldV) => {
    bill.value[4].selectData = paper_object_ype.value;
    keys.value = new Date().getTime();
  }
);
const drugListFun = () => {
  drugList(paginationParams.value).then((res:any) => {
    res.rows?.forEach((val) => {
      val.value = val.id
      val.label = val.name
    })
    bill.value[5].selectData = res.rows
    keys.value = new Date().getTime();
  })
}
drugListFun()

const handleQuery = function (): void {
  proxys.$refs.setUserSelect.submitForm().then((valid:any) => {

  if (valid.kind == 0) {
    let sun = 0
    topicList.value.forEach((val) => {
      sun+=val.score
    })
    if (sun != 100) {
      proxys.$modal.msgWarning('所以试题分值加起来要等于100分')
      return
    }
  }
    topicList.value.length && topicList.value.forEach((item) => {
      if(item.id.includes('row')){
        item.id = undefined
      }
    })
    valid.topicList = topicList.value;
    (!route.query.id ? addpaper : eitHpaper)(valid).then(() => {
      proxys.$modal.msgSuccess(`${route.query.id ? "修改" : "新增"}成功`);
      Cancel();
    });
  });
};
route.query.id && paperId(route.query.id).then((res) => {
  res.data.status = ''+res.data.status
  datas.value = res.data
  topicList.value = res.data.topicList
  listallFun()
})
const Cancel = () => {
  datas.value = {};
  const obj = { path: "/testPaper/examPaperManaList" };
  proxys.$tab.closeOpenPage(obj);
};
const promotionCostList = ref([])


// 输出
const fieldDefinitionColumn = ref([
  { type: 'seq', title: '序号', width: 60 },
  {
    field: "type",
     width: 100,
    title: "题号",
    slots: {
      default: ({ row }) => {
        return [<el-input v-model={row.type} placeholder="请输入题号" />];
      },
    },
  },
  {
    field: "topicId",
    title: "试题",
    slots: {
      default: ({ row }) => {
        return [ <el-select v-model={row.topicId} style={{width: '100%'}} class="m-2" placeholder="请选择试题">
          {promotionCostList.value.map(x => <el-option key={x.id} label={x.name} value={x.id}/>)}
        </el-select>];
      },
    },
  },
  {
    field: "score",
    title: "分值",
    width: 180,
    slots: {
      default: ({ row }) => {
        return [<el-input-number v-model={row.score} controls-position="right"/>];
      },
    },
  },
  {
    title: "操作",
    children: [
      {
        width: 100,
        slots: {
          header: ({ row }) => {
            return [
              <div
                style="cursor: pointer;"
                onClick={() => {
                  outListFun(row);
                }}
              >
                添加
              </div>,
            ];
          },
          default: ({ row }) => {
            return [
              <span
                style="color: red;cursor: pointer;"
                onClick={() => outListDelFun(row)}
              >
                删除
              </span>,
            ];
          },
        },
      },
    ]
  },
]);
const arr2Map = ref([])
const listallFun = () => {
  listall({
    objectType: datas.value.objectType,
    kind: datas.value.kind,
    drugId: datas.value.kind == 1? datas.value.drugId : '',
    pageNum: 1,
    pageSize: 1000,
  }).then((res:any) => {
    arr2Map.value = res.rows
    console.log('sdaga2141235', arr2Map.value)
  })
}
const topicListFun = () => {
  setdata({
    pageNum: 1,
    pageSize: 1000,
    kind: datas.value.kind,
    drugId: datas.value.drugId,
    objectType:  datas.value.objectType,
  }).then((res:any) => {
    promotionCostList.value = res.rows
  })
}
if (route.query.id) {
  setdata({
    pageNum: 1,
    pageSize: 1000,
  }).then((res:any) => {
    promotionCostList.value = res.rows
  })
}
const topicList = ref([])
const outListFun = async (data) => {
  if (datas.value.kind == 1) {
    if (!datas.value.kind || !datas.value.drugId || !datas.value.objectType) {
      proxys.$modal.msgWarning(`请先选择分类跟品种,对象再新增`);
      return
    }
  } else {
    if (!datas.value.kind || !datas.value.objectType) {
      proxys.$modal.msgWarning(`请先选择分类,对象再新增`);
      return
    }
  }
  
  await topicListFun()
  listallFun()
  topicList.value.push({
    type: (topicList.value.length + 1).toString(),
    score: '',
    topicId: '',
  })
  topicList.value = JSON.parse(JSON.stringify(topicList.value))
  // keyTimemin.value = new Date().getTime()
  // console.log(outList.value);
};

const outListDelFun =  (params:any): void => {
  topicList.value = topicList.value.filter((val) => val.id != params.id)
};

const istrueFun = (type, datas) => { 
  return (type.replace(/,/g, "") == datas)? false : true
}

</script>
<style scoped>
.pad_10 {
  padding: 10px;
}
.pad_10 .el-form--inline .el-form-item {
  margin: 0;
}
.el-divider--horizontal {
  margin: 10px 0;
}
.m-2 {
  width: 80%;
}
</style>
<style scoped>
  .pad_10 {
    padding: 10px;
    display: flex;
    height: calc(100vh - 100px);
    flex-direction: column;
    overflow: hidden;
  }
  .pad_10 .el-form--inline .el-form-item {
    margin: 0;
  }
  .el-divider--horizontal {
    margin: 10px 0;
  }
  .box-card{
    margin-bottom: 20px;
  }
  .card_box {
    flex: 1;
    overflow: hidden;
    overflow-y: scroll;
    padding: 10px;
    box-sizing: border-box;
  }
  </style>